package xmltomce;

import java.io.File;
import java.util.ArrayList;

public class MovieDbSynchronizer implements Runnable, MovieSyncNotifier {
	
	private ArrayList<MovieSyncObserver> observers = new ArrayList<MovieSyncObserver>();
	private File xmlDataSource;
	private File dvdFolderSource;
	private File mceInfoCacheTarget;
	
	
	public MovieDbSynchronizer(File xmlDataSurce, File dvdFolderSource, File mceInfoCacheTarget){
		this.xmlDataSource = xmlDataSurce;
		this.dvdFolderSource = dvdFolderSource;
		this.mceInfoCacheTarget = mceInfoCacheTarget;
	}
	
	@Override
	public void run() {
		if (filePathsAreValid()){
			synchronizeMediaCenterDb();
		}else{
			System.out.println("file paths are not valid!");
		}
	}
	
	private boolean filePathsAreValid(){
		return xmlDataSource.isFile() && 
			dvdFolderSource.isDirectory() && 
			mceInfoCacheTarget.isDirectory();
	}
	
	private void synchronizeMediaCenterDb(){
		XmlDataMatcher xdm = new XmlDataMatcher();
		ArrayList<Movie> movies = xdm.getMoviesWithXmlDescription(dvdFolderSource,xmlDataSource);
		notifyMovieFolderListSizeChanged(movies.size());
		
		for(int i=0; i<movies.size(); i++){
			Movie movie = movies.get(i);
			notifyMovieMatchDone(movie.getTitle());
			
			DvdFolderXmlWriter dfxw = new DvdFolderXmlWriter(movie);
			dfxw.saveXmlFile();
			
			InfoCacheXmlWriter icxw = new InfoCacheXmlWriter(mceInfoCacheTarget);
			icxw.saveXmlFile(movie);
		}
	}

	@Override
	public void addObserver(MovieSyncObserver observer) {
		observers.add(observer);
	}

	@Override
	public void removeObserver(MovieSyncObserver observer) {
		observers.remove(observer);
	}
	
	private void notifyMovieFolderListSizeChanged(int size){
		for(MovieSyncObserver observer: observers){
			observer.movieFolderListSizeChanged(size);
		}
	}
	
	private void notifyMovieMatchDone(String movieName){
		for(MovieSyncObserver observer : observers){
			observer.movieSyncDone(movieName);
		}
	}

}
